package com.etooling.framework.mobile;

import com.alibaba.fastjson.JSONObject;
import com.etooling.framework.entity.DataDir;
import com.etooling.framework.entity.Employee;
import com.etooling.framework.entity.PlatformAuth;
import com.etooling.framework.repository.ChineseAreaRepository;
import com.etooling.framework.repository.DataDirRepository;
import com.etooling.framework.repository.EmployeeRepository;
import com.etooling.framework.repository.PlatformAuthRepository;
import com.etooling.framework.svo.ReplyObj;
import com.etooling.framework.utils.CommonUtil;
import com.etooling.framework.utils.QywxUtil;
import com.etooling.framework.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Controller
@EnableAutoConfiguration
@RequestMapping(value = "/mobile/platformAuth")
public class PlatformAuthController {
    @Autowired
    ChineseAreaRepository chineseAreaRepository;

    @Autowired
    PlatformAuthRepository platformAuthRepository;

    public static Map<String, String> wxServerInfo = new HashMap<>();
    final String dataKey = "微信公众平台参数";

    @Autowired
    DataDirRepository dataDirRepository;

    //异步获取数据
    @RequestMapping("/getWeiXinUserInfo")
    @ResponseBody
    ReplyObj getWeiXinUserInfo(
            HttpServletRequest request,
            @RequestParam(defaultValue = "", required = false, value = "resCode") String resCode
    ) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            if (wxServerInfo.isEmpty()) {
                //到数据库拿公众号信息
                List<DataDir> dataDirs = dataDirRepository.getByGroupName(dataKey);
                for (DataDir d : dataDirs) {
                    wxServerInfo.put(d.getDisplayValue(), d.getDirValue());
                }
            }
            String wxAppid = wxServerInfo.get("wxAppid");
            String wxSecret = wxServerInfo.get("wxSecret");
            String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wxAppid + "&secret=" + wxSecret + "&code=" + resCode + "&grant_type=authorization_code";
            JSONObject jsonObject = CommonUtil.httpsRequest(URL, "GET", null);
            if (jsonObject.get("errcode") == "40029") {
                //token过期,刷新
                String refreshUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
                jsonObject = CommonUtil.httpsRequest(refreshUrl, "GET", null);
            }
            String token = "";
            //获取用户信息
            if (WebUtils.checkStr(jsonObject.get("access_token"))) {
                String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + jsonObject.get("access_token") + "&openid=" + jsonObject.get("openid") + "&lang=zh_CN";
                JSONObject userInfo = CommonUtil.httpsRequest(getUserInfoUrl, "GET", null);
                //如果获取到openid。直接用户表拿数据。
                PlatformAuth platformAuth = platformAuthRepository.getByOpenId(userInfo.getString("openid"), PlatformAuth.WEI_XIN_PLATFORM);
                if (platformAuth == null) {
                    platformAuth = new PlatformAuth();
                    String area = String.valueOf(userInfo.get("province"));
                    platformAuth.setPlatformOpenId(String.valueOf(userInfo.get("openid")));
                    platformAuth.setArea(area);
                    platformAuth.setNickName(String.valueOf(userInfo.get("nickname")));
                    platformAuth.setAvatar(String.valueOf(userInfo.get("headimgurl")));
                    platformAuth.setCreateTime(new Date());
                    platformAuth.setPlatformType(PlatformAuth.WEI_XIN_PLATFORM);
                    platformAuthRepository.save(platformAuth);
                }
                returnMap.put("platformAuth", platformAuth);
            } else {
                return WebUtils.flushFailure("微信登录失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return WebUtils.flushFailure("微信登录失败");
        }
        return WebUtils.flushSuccess(returnMap);
    }

    @RequestMapping("/getWxAppId")
    @ResponseBody
    ReplyObj getWxAppId(
            HttpServletRequest request,
            @RequestParam(defaultValue = "", required = false, value = "resCode") String resCode
    ) {
        if (wxServerInfo.isEmpty()) {
            //到数据库拿公众号信息
            List<DataDir> dataDirs = dataDirRepository.getByGroupName(dataKey);
            for (DataDir d : dataDirs) {
                wxServerInfo.put(d.getDisplayValue(), d.getDirValue());
            }
        }
        return WebUtils.flushObjSuccess(wxServerInfo.get("wxAppid"));
    }

    @Autowired
    EmployeeRepository employeeRepository;

    @RequestMapping("/getWXConfig")
    @ResponseBody
    ReplyObj getWXConfig(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "url") String url) {
        //1、获取AccessToken
        String accessToken = CommonUtil.getAccessToken();

        //2、获取Ticket
        String jsapi_ticket = CommonUtil.getTicket(accessToken);

        //3、时间戳和随机字符串
        String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳

        System.out.println("accessToken:" + accessToken + "\njsapi_ticket:" + jsapi_ticket + "\n时间戳：" + timestamp + "\n随机字符串：" + noncestr);

        //5、将参数排序并拼接字符串
        String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;

        //6、将字符串进行sha1加密
        String signature = CommonUtil.SHA1(str);
        HashMap map = new HashMap();
        map.put("timestamp", timestamp);
        map.put("nonceStr", noncestr);
        map.put("signature", signature);
        return WebUtils.flushSuccess(map);
    }


    @RequestMapping("/getEmployeeByQyWx")
    @ResponseBody
    ReplyObj getEmployeeByQyWx(HttpServletRequest request,
                               @RequestParam(defaultValue = "", required = false, value = "code") String code) {
        String companyId = WebUtils.getSessionValue(request, WebUtils.LOGIN_COMPANY_ID_KEY);
        JSONObject jsonObject = QywxUtil.getInstance(companyId).getQywxUserInfo(code);
        String qxWxEmployeeId = jsonObject.getString("userid");
        if (!WebUtils.checkStr(qxWxEmployeeId)) {
            return WebUtils.flushFailure();
        }
        PlatformAuth platformAuth = platformAuthRepository.getByOpenId(qxWxEmployeeId, PlatformAuth.QY_WEI_XIN_PLATFORM);
        if (platformAuth == null) {
            platformAuth = new PlatformAuth();
            platformAuth.setPlatformOpenId(qxWxEmployeeId);
            platformAuth.setPlatformType(PlatformAuth.QY_WEI_XIN_PLATFORM);
            platformAuth.setMobile(jsonObject.getString("mobile"));
            platformAuth.setAvatar(jsonObject.getString("avatar"));
            platformAuth.setSex("1".equals(jsonObject.getString("gender")) ? "男" : "女");
            platformAuth.setCreateTime(new Date());
            platformAuthRepository.save(platformAuth);
            List<PlatformAuth> platformAuths = new ArrayList<>();
            platformAuths.add(platformAuth);

            Employee employee = employeeRepository.getOneByMobile(platformAuth.getMobile());
            if (!WebUtils.checkStr(employee)) {
                employee = new Employee();
                employee.setCreateTime(new Date());
                employee.setAvatarUrl(platformAuth.getAvatar());
                employee.setGender(platformAuth.getSex());
                employee.setEmployeeCode(platformAuth.getPlatformOpenId());
                employee.setName(platformAuth.getPlatformOpenId());
                employee.setCompanyId(companyId);
                employee.setPlatformAuths(platformAuths);
                employee.setStatus(Employee.RUNNING_STATUS);
                employee.setMobile(platformAuth.getMobile());
                employeeRepository.save(employee);
            }
            String token = "";
            token = WebUtils.setSessionValue(token, WebUtils.LOGIN_USER_KEY, employee.getId());
            token = WebUtils.setSessionValue(token, WebUtils.LOGIN_COMPANY_ID_KEY, companyId);
            //WebUtils.setSessionValue(token, WebUtils.LOGIN_ORG_ID_KEY, employee.getOrg().getId());
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("employee",employee);
            returnMap.put("token",token);
            return WebUtils.flushSuccess(returnMap);
        } else {
            List<Employee> employees = employeeRepository.getEmployeeByPlatformAuthId(platformAuth.getId());
            if (!employees.isEmpty()) {
                String token = "";
                token = WebUtils.setSessionValue(token, WebUtils.LOGIN_USER_KEY, employees.get(0).getId());
                token = WebUtils.setSessionValue(token, WebUtils.LOGIN_COMPANY_ID_KEY, companyId);
                //WebUtils.setSessionValue(token, WebUtils.LOGIN_ORG_ID_KEY, employees.get(0).getOrg().getId());
                Map<String, Object> returnMap = new HashMap<>();
                returnMap.put("employee",employees.get(0));
                returnMap.put("token",token);
                return WebUtils.flushSuccess(returnMap);
            }
            return WebUtils.flushSuccess();
        }

    }

    @RequestMapping("/getQyWxConfig")
    @ResponseBody
    ReplyObj getQyWxConfig(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "url") String url) {
        String companyId = WebUtils.getSessionValue(request, WebUtils.LOGIN_COMPANY_ID_KEY);
        String ticket = QywxUtil.getInstance(companyId).getJsApiTicket();
        if (WebUtils.checkStr(ticket)) {
            String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳
            //6、将字符串进行sha1加密
            String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
            String signature = CommonUtil.SHA1(str);
            String appId = QywxUtil.getInstance(companyId).getCorpId();
            HashMap map = new HashMap();
            map.put("timestamp", timestamp);
            map.put("nonceStr", noncestr);
            map.put("signature", signature);
            map.put("appId", appId);
            return WebUtils.flushSuccess(map);
        } else {
            return WebUtils.flushFailure("获取认证失败！");
        }
    }

    @RequestMapping("/getQyWxAgentConfig")
    @ResponseBody
    ReplyObj getQyWxAgentConfig(HttpServletRequest request, @RequestParam(defaultValue = "", required = false, value = "url") String url) {
        String companyId = WebUtils.getSessionValue(request, WebUtils.LOGIN_COMPANY_ID_KEY);
        String ticket = QywxUtil.getInstance(companyId).getJsAgentSignTicket();
        if (WebUtils.checkStr(ticket)) {
            String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳
            //6、将字符串进行sha1加密
            String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
            String signature = CommonUtil.SHA1(str);
            String agentid = QywxUtil.getInstance(companyId).getAgentId();
            String appId = QywxUtil.getInstance(companyId).getCorpId();
            HashMap<String, String> map = new HashMap();
            map.put("timestamp", timestamp);
            map.put("nonceStr", noncestr);
            map.put("signature", signature);
            map.put("appId", appId);
            map.put("agentid", agentid);
            return WebUtils.flushSuccess(map);
        } else {
            return WebUtils.flushFailure("获取领证失败！");
        }
    }

    @RequestMapping("/getQyInfo")
    @ResponseBody
    ReplyObj getQyInfo(HttpServletRequest request) {
        String companyId = WebUtils.getSessionValue(request, WebUtils.LOGIN_COMPANY_ID_KEY);
        //6、将字符串进行sha1加密
        String agentid = QywxUtil.getInstance(companyId).getAgentId();
        String appId = QywxUtil.getInstance(companyId).getCorpId();
        HashMap<String, String> map = new HashMap();
        map.put("appId", appId);
        map.put("agentid", agentid);
        return WebUtils.flushSuccess(map);
    }


}


